//
//  BLApi.m
//  BasketBallLeagues
//
//  Created by kenshin on 4/25/17.
//  Copyright © 2017 kenshin. All rights reserved.
//

#import "BLApi.h"

@implementation BLExampleCommentSupport

@end

@implementation BLApi


#pragma mark - 初步封装
+ (void)commonGET:(nonnull NSString *)URLString
       parameters:(nullable NSDictionary *)parameters
          success:(nullable BLAPICommonSucccessBlock)successBlock
           failed:(nullable BLAPICommonErrorBlock)failedBlock {
    [self GET:URLString parameters:parameters decodeClass:[BLBaseResponse class] completion:^(id responseObject, id responseDataOriginal, NSError *error) {
        if (error) {
            [self ks_showToast:@"网络错误"];
            if (failedBlock) {
                failedBlock(responseObject, responseDataOriginal, error);
            }
            
            return;
        }
        BLBaseResponse *response = (BLBaseResponse *)responseObject;
        if ([response isSuccess]) {
            if (successBlock) {
                successBlock(responseObject, responseDataOriginal);
            }
        } else {
            //==
            [self ks_showToast:response.errmsg];
            if (failedBlock) {
                failedBlock(responseObject, responseDataOriginal, error);
            }
        }
    }];
}

+ (void)commonGET:(NSString *)URLString
       parameters:(NSDictionary *)parameters
       completion:(BLAPICommonSucccessBlock)completion {
    [self commonGET:URLString parameters:parameters success:completion failed:nil];
}


+ (void)commonPOST:(nonnull NSString *)URLString
        parameters:(nullable NSDictionary *)parameters
           success:(nullable BLAPICommonSucccessBlock)successBlock
            failed:(nullable BLAPICommonErrorBlock)failedBlock {
    [self POST:URLString parameters:parameters decodeClass:[BLBaseResponse class] completion:^(id responseObject, id responseDataOriginal, NSError *error) {
        if (error) {
            [self ks_showToast:@"网络错误"];
            if (failedBlock) {
                failedBlock(responseObject, responseDataOriginal, error);
            }
            return;
        }
        
        BLBaseResponse *response = (BLBaseResponse *)responseObject;
        if ([response isSuccess]) {
            if (successBlock) {
                successBlock(responseObject, responseDataOriginal);
            }
        } else {
            [self ks_showToast:response.errmsg];
            if (failedBlock) {
                failedBlock(responseObject, responseDataOriginal, error);
            }
        }
    }];
}

+ (void)commonPOST:(NSString *)URLString
        parameters:(NSDictionary *)parameters
        completion:(BLAPICommonSucccessBlock)completion {
    [self commonPOST:URLString parameters:parameters success:completion failed:nil];
}



+ (BLBaseRequestGet *)GET:(NSString *)URLString
               parameters:(NSDictionary *)parameters
              decodeClass:(Class)decodeClass
               completion:(KSRequestCompletionBlock)completion {
    return (BLBaseRequestGet *)[self Request:YES URLString:URLString param:parameters decodeClass:decodeClass completion:completion];
}

+ (BLBaseRequestGet *)GET:(NSString *)URLString
               paramModel:(KSBaseRequestParam *)paramModel
              decodeClass:(Class)decodeClass
               completion:(KSRequestCompletionBlock)completion {
    return (BLBaseRequestGet *)[self Request:YES URLString:URLString param:paramModel decodeClass:decodeClass completion:completion];
}

+ (BLBaseRequestPost *)POST:(NSString *)URLString
                 parameters:(NSDictionary *)parameters
                decodeClass:(Class)decodeClass
                 completion:(KSRequestCompletionBlock)completion {
    return (BLBaseRequestPost *)[self Request:NO URLString:URLString param:parameters decodeClass:decodeClass completion:completion];
}

+ (BLBaseRequestPost *)POST:(NSString *)URLString
                 paramModel:(KSBaseRequestParam *)paramModel
                decodeClass:(Class)decodeClass
                 completion:(KSRequestCompletionBlock)completion {
    return (BLBaseRequestPost *)[self Request:NO URLString:URLString param:paramModel decodeClass:decodeClass completion:completion];
}


+ (BLBaseRequest *)Request:(BOOL)isGet
                 URLString:(NSString *)URLString
                     param:(id)param
               decodeClass:(Class)decodeClass
                completion:(KSRequestCompletionBlock)completion {
    BLBaseRequest *request = nil;
    if (isGet) {
        request = [BLBaseRequestGet new];
    } else {
        request = [BLBaseRequestPost new];
    }
    request.url = URLString;
    if ([param isKindOfClass:[NSDictionary class]]) {
        request.extra_param_dict = param;
    } else {
        request.extra_param_model = param;
    }
    
    Class currentDecodeClass = decodeClass;
    if (decodeClass == nil) {
//        currentDecodeClass = [BLBaseResponse class];
    }
    
    [self startRequest:request decodeClass:currentDecodeClass completion:completion];
    return request;
}

+ (void)startRequest:(BLBaseRequest *)request
         decodeClass:(Class)decodeClass
          completion:(KSRequestCompletionBlock)completion
{
    DDLogInfo(@"请求url:%@", [request fullURL]);
    [request startRequestWithDecodeClass:decodeClass completion:completion];
}


+ (void)exampleCommentSupportByDict:(NSInteger)commentID {
    [self POST:@"comment/support" parameters:@{@"cid":@(commentID)} decodeClass:nil completion:nil];
}

+ (void)exampleCommentSupport:(BLExampleCommentSupport *)commentID {
    [self POST:@"comment/support" paramModel:commentID decodeClass:nil completion:nil];
}


/**
 *  长传图片文件
 *
 *  @param url         url
 *  @param imageData          图片
 *  @param didFinishBlock 回调
 */
+(void) PostImageToUrl:(NSString *)url
                 image:(NSData *)imageData
                Params:(NSDictionary *)params
             didFinish:(void(^)(id json,NSError *error))didFinishBlock
{
    AFHTTPSessionManager *manager = [self encapsulationManger];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 30;
  
    dispatch_async(dispatch_get_main_queue(), ^{
        //在向服务端发送请求状态栏显示网络活动标志：
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    });
    
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData :imageData name:@"image" fileName:@"file.png" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //请求结束状态栏隐藏网络活动标志：
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"url:%@,responseObject: %@",url, jsonString);
        
        didFinishBlock(responseObject,nil);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //请求结束状态栏隐藏网络活动标志：
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
        didFinishBlock(nil,error);
    }];
}

/**
 *  上传多张图片到服务器
 *
 *  @param url            url
 *  @param params     参数
 *  @param imageDatas     data数组
 *  @param didFinishBlock 回调
 */
+(void)PostImagesToUrl:(NSString *)url
             SetParams:(NSDictionary *)params
            ImageDatas:(NSMutableArray *)imageDatas
             didFinish:(void(^)(id json,NSError *error))didFinishBlock
{
    // 向服务器提交图片
    AFHTTPSessionManager *manager = [self encapsulationManger];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        //在向服务端发送请求状态栏显示网络活动标志：
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    });
    
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for(NSInteger i = 0; i < imageDatas.count; i++)
        {
            NSData * imageData = [imageDatas objectAtIndex:i];
            [formData appendPartWithFileData:imageData name:@"image" fileName:@"file.png" mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //结束显示网络活动标志：
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
//        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"url:%@,responseObject: %@",url, jsonString);
        
        didFinishBlock(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //结束显示网络活动标志：
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        
        didFinishBlock(nil,error);
    }];
}

+ (NSString *)configSign:(NSString *)userId andCurtime:(NSString *)curtime {
    NSString *sign = [NSString stringWithFormat:@"%@%@%@",userId,curtime,@"yichangyanchu"];
    DDLogInfo(@"%@",sign);
    NSString *result = [sign jc_md5];
    NSString *newSign = [result lowercaseString];
    return newSign;
}

//设置固定的请求头
+ (AFHTTPSessionManager *)encapsulationManger{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//
//    NSString *device = @"1";
//    NSString *curtime = [PublicTool getNowTimeStamp];
//    NSString *os_version = [SystemHelper osVersion];
//    NSString *version = [SystemHelper appVersion];
//    NSString *user_id = @"0";
//    NSString *sign = [BLApi configSign:user_id andCurtime:curtime];
//    //拼接sign
//    if ([TKAccountManager isLogin]) {
//        user_id = [TKAccountManager sharedManager].accountInfo.result.info.user_id;
//        sign = [BLApi configSign:user_id andCurtime:curtime];
//    }
//    [manager.requestSerializer setValue:device forHTTPHeaderField:@"device"];
//    [manager.requestSerializer setValue:curtime forHTTPHeaderField:@"curtime"];
//    [manager.requestSerializer setValue:os_version forHTTPHeaderField:@"os_version"];
//    [manager.requestSerializer setValue:version forHTTPHeaderField:@"version"];
//    [manager.requestSerializer setValue:user_id forHTTPHeaderField:@"user_id"];
//    [manager.requestSerializer setValue:sign forHTTPHeaderField:@"sign"];

    
    return  manager;
    
}
@end
